<template>
  <bc-modal :size="[450, 65]" type="dialog" title="赠送券" v-model="dialogVisible" footer>
    <el-form ref="ruleFormRef" label-position="right" :model="formData" label-width="auto">
      <bc-form
        ref="bcFormRef"
        :border="false"
        padding="0"
        :fields="formOptions"
        :cols="1"
        mode="add"
        @change="handleChange"
      >
      </bc-form>
    </el-form>
    <template #footer>
      <el-button @click="colse">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </template>
  </bc-modal>
</template>

<script setup>
import BcModal from '@/components/BcModal.vue'
import BcForm from '@/components/bcForm/Index.vue'

const formOptions = [
  {
    label: '奖券',
    prop: 'rewardId',
    type: 'select',
    options: async () => {
      try {
        const params = {
          pageNum: 1,
          pageSize: 1000,
        }
        const res = await $request.post('/api-parking/parking/reward/queryReward', { params })
        return (res.rows || []).map((item) => ({
          label: item.name,
          value: item.id,
        }))
      } catch (error) {
        return []
      }
    },
    rules: [{ required: true, message: '奖券不能为空' }],
  },
]
const emits = defineEmits(['change'])

const dialogVisible = ref(false)
const open = (info) => {
  Object.keys(formData).forEach((key) => {
    formData[key] = ''
  })
  Object.assign(formData, info)
  dialogVisible.value = true
}
const colse = () => {
  dialogVisible.value = false
}
const onSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          ...formData,
        }
        await $request.post('/api-parking/parking/prize/rollPrize', { params })
        ElMessage({ type: 'success', message: '操作成功' })
        emits('change')
        colse()
      } catch (error) {
        return Promise.reject(error)
      }
    }
    return false
  })
}

const ruleFormRef = ref(null)
const bcFormRef = ref(null)
const formData = reactive({})
const handleChange = (value) => {
  Object.assign(formData, value.value)
}

watch(
  () => dialogVisible.value,
  (newVal) => {
    if (newVal === false) {
      bcFormRef.value.reset()
    }
  }
)

defineExpose({
  open,
})
</script>

<style lang="scss" scoped></style>
